package _interview150;

import java.util.HashMap;
import java.util.Map;

/**
 * 138. 随机链表的复制
 */
public class No138 {
    public Node copyRandomList(Node head) {
        Node cur = new Node(-1), dummy = new Node(-1);
        dummy.next = cur;
        Map<Node, Node> map = new HashMap<>();
        while (head != null) {
            cur.next = new Node(head.val);
            cur = cur.next;
            map.put(head, cur);
            head = head.next;
        }
        map.forEach((k, v) -> v.random = map.get(k.random));
        return dummy.next.next;
    }

    private static class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }
}
